import json
import os
import multiprocessing
import time

import requests
from flask_cors import CORS
from flask import Flask, Response, request
from util import get_token
mainApp=Flask(__name__)
CORS(mainApp)

process_list=[]
@mainApp.route('/start',methods=['POST','GET'])
def start():
    data=request.get_data()
    data=json.loads(data)
    ahead_src=data["ahead"]
    back_src=data["back"]
    group_1=[ahead_src[i] for i in range(0,8)]
    group_2=[ahead_src[i] for i in range(8,15)]
    group_3=[back_src
             [i] for i in range(0,8)]
    group_4=[back_src[i] for i in range(8,15)]

def run_flask(app_module_name,port,gpu_id):
    os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
    # 根据传入的应用名称动态导入对应的 Flask 应用创建函数
    app_module = __import__(app_module_name)
    app_class = getattr(app_module, app_module_name.capitalize())
    app_instance = app_class(str(gpu_id))
    app_instance.run(host="0.0.0.0", port=port)

def run_process():
    # port = [5000, 5010, 5020, 5030]
    # p1 = multiprocessing.Process(target=run_flask, args=("appFront", port[0], 0))
    # p1.start()
    # process_list.append(p1)
    #
    # p2 = multiprocessing.Process(target=run_flask, args=("appFront", port[1], 1))
    # p2.start()
    # process_list.append(p2)
    #
    # p3 = multiprocessing.Process(target=run_flask, args=("appBack", port[2], 2))
    # p3.start()
    # process_list.append(p3)
    #
    # p4 = multiprocessing.Process(target=run_flask, args=("appBack", port[3], 3))
    # p4.start()
    # process_list.append(p4)

    # front_port1 = [5001, 5002, 5003, 5004,5005]
    # back_port=[5031,5032,5033,5034,5035]
    front_port1 = [5001]
    back_port=[5032]
    gpu_id = 0
    for port in front_port1:
        if port > 5003:
            gpu_id = 1
        else:
            gpu_id = 0
        p = multiprocessing.Process(target=run_flask, args=("appFront", port, gpu_id))
        p.start()
        process_list.append(p)
    for port in back_port:
        if port > 5033:
            gpu_id = 2
        else:
            gpu_id = 3
        p = multiprocessing.Process(target=run_flask, args=("appBack", port, gpu_id))
        p.start()
        process_list.append(p)




    # p1 = multiprocessing.Process(target=run_flask, args=("appFront", port[0], 0))
    # p1.start()
    # process_list.append(p1)
    #
    # # 启动 app2 实例
    # # port2 = 5000 + 1 * 10
    # p2 = multiprocessing.Process(target=run_flask, args=("appFront", port[1], 1))
    # p2.start()
    # process_list.append(p2)
    #
    # # 启动 appTeacher1 实例
    # p3 = multiprocessing.Process(target=run_flask, args=("appFront", port[2], 2))
    # p3.start()
    # process_list.append(p3)
    #
    # # 启动 appTeacher2 实例
    # # port4 = 6000 + 3 * 10
    # p4 = multiprocessing.Process(target=run_flask, args=("appBack", port[3], 3))
    # p4.start()
    # process_list.append(p4)
    # for p in process_list:
    #     p.join()
    return process_list

if __name__ == '__main__':
    # 启动Flask进程
    flask_processes = run_process()
#     time.sleep(4)
#     url="http://127.0.0.1:5000/start"
#     data=[{
#     "path":"F:\shuju\end_video\\front_1_1",
#     "camera_id":1,
#     "person_type":1
# }
# ]

    # data=json.dumps(data)
    # res=requests.post(url,data=data)
    # print(res)

    # 等待所有Flask进程结束
    for process in flask_processes:
        process.join()
#     import socket
#     def is_port_ready(host, port):
#         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#         try:
#             s.connect((host, port))
#             s.shutdown(socket.SHUT_RDWR)
#             return True
#         except ConnectionRefusedError:
#             return False
#         finally:
#             s.close()
#
#
#     # 要检查的主机和端口
#     host = 'localhost'
#     port = 5000
#
#     if is_port_ready(host, port):
#         print(f"Port {port} on {host} is ready")
#     else:
#         print(f"Port {port} on {host} is not ready")




